﻿using UnityEngine;
using System.Collections;

public class LandOnStart : MonoBehaviour {

	public float for_how_long = 1f;
	public Vector3 dir = Vector3.down;
	public Vector2 randomize_dir = Vector2.zero;
	public float dist = 0.5f;
	private int layer =0 ;
	void Land()
	{
		//Vector3 extents = transform.collider2D.bounds.size;
		//Vector3 plr_bottom = new Vector3(0,extents.y,0f);
		Vector3 ray_origin = transform.position;// - plr_bottom;

		
		
		//RaycastHit2D ground = Physics2D.Raycast(ray_origin,-Vector2.up,100f,LayerMask.NameToLayer("Ground"));
		
		
		float rx = (float) (Random.Range(-100,100))/100f;
		float ry = (float) (Random.Range(-100,100))/100f;
		
		dir.x += rx*randomize_dir.x;
		dir.y += ry*randomize_dir.y;
		dir.z = 0f;
		dir.Normalize();
		
		RaycastHit2D ground = Physics2D.Raycast(ray_origin,dir,100f);
		
		
		if(ground.point.y != 0)
		{
			//if(ground.collider.gameObject.layer == LayerMask.NameToLayer("Ground"))
				transform.position = new Vector3(ground.point.x,ground.point.y,0f) - dir*dist;
			/*
			else
			{
				if(ground.collider.rigidbody2D != null)
				{
					if(ground.collider.rigidbody2D.IsSleeping())
						transform.position = new Vector3(ground.point.x,ground.point.y,0f) - dir*dist;
				}
			}*/
		}
	}
	
	
	void Start () {
		
		layer =	gameObject.layer;
		gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
		
		Land();
		
	}
	void Update () {

		if(Time.timeSinceLevelLoad < for_how_long)// || Input.GetKey(KeyCode.Q))
			Land();
		else
			gameObject.layer = layer;
		
	}
}
